package com.useeinfo.oa.modules.threadUtil.thread;

import com.useeinfo.framework.sugar.func.excel.ExcelImport;
import com.useeinfo.framework.sugar.func.excel.ExcelImportParam;
import com.useeinfo.framework.sugar.func.excel.ExcelMapImport;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.vo.FacilityVO;
import com.useeinfo.oa.modules.logger.biz.FacilityLogBiz;
import com.useeinfo.oa.modules.logger.entity.FacilityLog;
import com.useeinfo.oa.modules.logger.enums.LogTypeEnum;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class FacilityThread extends Thread {
    private final static Logger logger = LoggerFactory.getLogger(FacilityThread.class);
    private FacilityImportBiz facilityImportBiz;
    private FacilityLogBiz facilityLogBiz;
    private FacilityBiz facilityBiz;
    private FacilityGroupBiz facilityGroupBiz;
    private FacilityCatBiz facilityCatBiz;
    private AreaBiz areaBiz;
    private OrganizationBiz organizationBiz;
    private FacilityImport facilityImport;

    public FacilityThread(FacilityImportBiz facilityImportBiz, FacilityBiz facilityBiz, FacilityLogBiz facilityLogBiz,FacilityGroupBiz facilityGroupBiz,FacilityCatBiz facilityCatBiz,AreaBiz areaBiz,OrganizationBiz organizationBiz, FacilityImport facilityImport) {
        this.facilityImportBiz = facilityImportBiz;
        this.facilityBiz = facilityBiz;
        this.facilityImport = facilityImport;
        this.facilityLogBiz = facilityLogBiz;
        this.facilityGroupBiz = facilityGroupBiz;
        this.facilityCatBiz = facilityCatBiz;
        this.areaBiz = areaBiz;
        this.organizationBiz = organizationBiz;
    }

    @Override
    public synchronized void run() {
        logger.info("开始执行--查询需要导入的文件进行导入");
        Enterprise enterprise = facilityImport.getEnterprise();
        if (enterprise == null) {
            return;
        }
        String filePath = Configuration.getConfigurationByName("fileSaveRootPath");
        filePath += filePath.endsWith("/") ? "" : "/";
        String savePath = facilityImport.getFilePath();
        // 获取上传excel绝对路径
        String fullPath = filePath + savePath;
        // 获取excel文件中列与对象对应关系
        ExcelImportParam excelImportParam = new ExcelImportParam();
        excelImportParam.setCellPropertyMap(ExcelMapImport.facilityImport());
        // 将excel中数据读入对象
        List<FacilityVO> facilityVOs = ExcelImport.readExcel(fullPath, FacilityVO.class, excelImportParam);
        if (CollectionUtils.isEmpty(facilityVOs)) {
            facilityImport.setStatus("1");
            facilityImportBiz.addOrUpdate(facilityImport);
            return;
        }
        for (int i = 0; i < facilityVOs.size(); i++) {
            int j = i+2;
            FacilityVO facilityVO = facilityVOs.get(i);
            String name = facilityVO.getName();
            String code = facilityVO.getCode();
            String serialNum = facilityVO.getSerialNum();
            String factory = facilityVO.getFactory();
            String position = facilityVO.getPosition();
            String precisePosition = facilityVO.getPrecisePosition();
            String detailPosition = facilityVO.getDetailPosition();
            String longitudeParam = facilityVO.getLongitude();
            String latitudeParam = facilityVO.getLatitude();
            String importantDegree = facilityVO.getImportantDegree();
            String guarantee = facilityVO.getGuarantee();
            String releaseDate = facilityVO.getReleaseDate();
            String enableDate = facilityVO.getEnableDate();
            String purpose = facilityVO.getPurpose();
            String mainParm = facilityVO.getMainParm();
            String upPower = facilityVO.getUpPower();
            String sparePower = facilityVO.getSparePower();
            String power = facilityVO.getPower();
            String indoor = facilityVO.getIndoor();
            String effective = facilityVO.getEffective();
            String belongSystem = facilityVO.getBelongSystem();
            String subSystem = facilityVO.getSubSystem();
            String costCenter = facilityVO.getCostCenter();
            String gridPerson = facilityVO.getGridPerson();
            String qrCode = facilityVO.getQrCode();
            String faCode = facilityVO.getFaCode();
            String type = facilityVO.getType();
            String parentFacilityCode = facilityVO.getParentFacilityCode();
            String areaId = facilityVO.getAreaId();
            String facilityGroupId = facilityVO.getFacilityGroupId();
            String facilityCatId = facilityVO.getFacilityCatId();
            String organizationId = facilityVO.getOrganizationId();

            //必要参数不得为空
            if (StringUtils.isEmpty(name)
                    || StringUtils.isEmpty(code)) {
                facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[设备名或设备编码为空];\n");
                facilityImportBiz.addOrUpdate(facilityImport);
                continue;
            }
            Facility facility = facilityBiz.getFacilityByCode(code,enterprise.getId()+"");
            if(facility==null){
                facility = new Facility();
                facility.setCode(code);
                facility.setQrCode(code);
            }
            if(StringUtils.isNotBlank(qrCode)){
                facility.setQrCode(qrCode);
            }

            if (facilityBiz.existFacility(facility, enterprise.getId())) {
                facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[设备编码/二维码重复];\n");
                facilityImportBiz.addOrUpdate(facilityImport);
                continue;
            }
            //不需要覆盖的字段
            if(facility.getId()==null){
                facility.setEnterprise(enterprise);
                facility.setSerialCode(facilityBiz.getSerialCode(enterprise.getId()+""));

            }
            //需要覆盖的字段
            facility.setName(name);
            if(StringUtils.isNotBlank(serialNum)){
                facility.setSerialNum(serialNum);
            }
            if(StringUtils.isNotBlank(factory)){
                facility.setFactory(factory);
            }
            if(StringUtils.isNotBlank(position)){
                facility.setPosition(position);
            }
            if(StringUtils.isNotBlank(precisePosition)){
                facility.setPrecisePosition(precisePosition);
            }
            if(StringUtils.isNotBlank(detailPosition)){
                facility.setDetailPosition(detailPosition);
            }
            if(StringUtils.isNotBlank(importantDegree)){
                facility.setImportantDegree(importantDegree);
            }
            if(StringUtils.isNotBlank(guarantee)){
                facility.setGuarantee(guarantee);
            }
            if(StringUtils.isNotBlank(purpose)){
                facility.setPurpose(purpose);
            }
            if(StringUtils.isNotBlank(mainParm)){
                facility.setMainParm(mainParm);
            }
            if(StringUtils.isNotBlank(upPower)){
                facility.setUpPower(upPower);
            }
            if(StringUtils.isNotBlank(sparePower)){
                facility.setSparePower(sparePower);
            }
            if(StringUtils.isNotBlank(belongSystem)){
                facility.setBelongSystem(belongSystem);
            }
            if(StringUtils.isNotBlank(subSystem)){
                facility.setSubSystem(subSystem);
            }
            if(StringUtils.isNotBlank(costCenter)){
                facility.setCostCenter(costCenter);
            }
            if(StringUtils.isNotBlank(gridPerson)){
                facility.setGridPerson(gridPerson);
            }
            if(StringUtils.isNotBlank(faCode)){
                facility.setFaCode(faCode);
            }
            if(StringUtils.isNotBlank(type)){
                facility.setType(type);
            }
            if(StringUtils.isNotBlank(power)){
                facility.setPower(power);
            }
            if("1".equals(indoor)){
                facility.setIndoor(true);
            }
            if("1".equals(effective)){
                facility.setEffective(true);
            }
            //判断经纬度
            if (StringUtils.isNotBlank(longitudeParam)) {
                Double longitude;
                try {
                    longitude = Double.parseDouble(longitudeParam);
                } catch (Exception e) {
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[经纬度数据异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
                if (longitude > 180D || longitude < -180D) {
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[经纬度数据异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
                facility.setLongitude(longitude);
            }
            if (StringUtils.isNotBlank(latitudeParam)) {
                Double latitude;
                try {
                    latitude = Double.parseDouble(latitudeParam);
                } catch (Exception e) {
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[经纬度数据异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
                if (latitude > 90D || latitude < -90D) {
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[经纬度数据异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
                facility.setLatitude(latitude);
            }
            //判断时间
            if(StringUtils.isNotBlank(releaseDate)){
                try{
                    facility.setReleaseDate(DateTimeUtils.parse("yyyy-MM-dd",releaseDate));
                }catch (Exception e){
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[出厂日期格式异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
            }
            if(StringUtils.isNotBlank(enableDate)){
                try{
                    facility.setEnableDate(DateTimeUtils.parse("yyyy-MM-dd",enableDate));
                }catch (Exception e){
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[启用日期格式异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
            }
            //上级设备
            if(StringUtils.isNotBlank(parentFacilityCode)){
                Facility parentFacility = facilityBiz.getFacilityByCode(parentFacilityCode,enterprise.getId()+"");
                if(parentFacility==null||(facility.getId()!=null&&parentFacility.getId().equals(facility.getId()))){
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[上级设备参数异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
                facility.setParentId(parentFacility.getId());
                facility.setParentName(parentFacility.getName());
            }
            //所属分组
            if(StringUtils.isNotBlank(facilityGroupId)){
                FacilityGroup facilityGroup = facilityGroupBiz.findModel(StringConverters.ToLong(facilityGroupId));
                if(facilityGroup==null){
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[所属分组参数异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
                facility.setFacilityGroup(facilityGroup);
            }
            //所属分类
            if(StringUtils.isNotBlank(facilityCatId)){
                FacilityCat facilityCat = facilityCatBiz.findModel(StringConverters.ToLong(facilityCatId));
                if(facilityCat==null||facilityCat.getLvl()==0||facilityCat.getEnterprise()==null||!facilityCat.getEnterprise().getId().equals(enterprise.getId())){
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[所属类型参数异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
                facility.setFacilityCat(facilityCat);
                facility.setRootCatId(facilityCatBiz.findRootCat(facilityCat.getId()).getId());
            }
            //所属区域
            if(StringUtils.isNotBlank(areaId)){
                Area area = areaBiz.findModel(StringConverters.ToLong(areaId));
                if(area==null||area.getEnterprise()==null||!area.getEnterprise().getId().equals(enterprise.getId())){
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[所属区域参数异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
                facility.setArea(area);
            }
            //所属组织
            if(StringUtils.isNotBlank(organizationId)){
                Organization organization = organizationBiz.findModel(StringConverters.ToLong(organizationId));
                if(organization==null||organization.getEnterprise()==null||!organization.getEnterprise().getId().equals(enterprise.getId())){
                    facilityImport.setErrorCount(facilityImport.getErrorCount() + 1);
                    facilityImport.setErrorData(StringConverters.null2String(facilityImport.getErrorData())+"行数:["+j+"] 异常原因:[所属组织参数异常];\n");
                    facilityImportBiz.addOrUpdate(facilityImport);
                    continue;
                }
                facility.setOrganization(organization);
            }
            facilityBiz.addOrUpdate(facility);
            //添加日志
            FacilityLog facilityLog = new FacilityLog();
            facilityLog.setLogTypeEnum(LogTypeEnum.importExcel);
            facilityLog.setUserName(facilityImport.getSystemUserName());
            facilityLog.setUserId(facilityImport.getSystemUserId());
            facilityLog.setFacilityId(facility.getId());
            facilityLog.setContent("[批量导入]facilityImportId:" + facilityImport.getId());
            facilityLogBiz.addOrUpdate(facilityLog);
            facilityImport.setFinishCount(facilityImport.getFinishCount() + 1);
            facilityImportBiz.addOrUpdate(facilityImport);
        }
        //循环结束后设为已完成
        facilityImport.setStatus("1");
        facilityImportBiz.addOrUpdate(facilityImport);
        logger.info("结束执行--查询需要导入的文件进行导入");
    }
}
